<template>
  <view class="member-list-page">
    <nav-bar title="我的会员" ref="navBarRef" />
    <view ref="searchBarRef" class="search-bar">
      <u-input
        v-model="params.businessName"
        placeholder="请输入商户名称"
        border="surround"
        shape="circle"
        prefixIcon="search"
        :customStyle="searchCustomStyle"
        @blur="handleSearch"
      >
        <template slot="suffix">
          <view
            class="search-text"
            :style="{ color: themeColor }"
            @click="handleSearch"
            >搜索</view
          >
        </template>
      </u-input>
    </view>
    <scroll-view
      v-if="list.length > 0"
      scroll-y
      class="member-list"
      @scrolltolower="handleScrollToLower"
      :style="{
        height: `calc(100vh - ${navBarHeight}px - env(safe-area-inset-bottom) - 24px)`,
      }"
    >
      <view v-for="item in list" :key="item.id" class="list-item">
        <!--        头部 -->
        <view class="item-header flex-align-center">
          <view class="item-header-left flex-align-center">
            <u-avatar :src="item.logoUrl" size="67rpx" />
            <text class="businessName">{{ item.businessName }}</text>
          </view>
          <view
            v-if="item.hasMore"
            class="item-header-right"
            :style="{ color: themeColor, fontSize: '27rpx' }"
            @click="handleInnitShopList(item, true)"
            >所有门店</view
          >
        </view>
        <!--        信息主体-->
        <member-list-item
          :logo="item.logo"
          :latitude="item.shopVo.latitude"
          :longitude="item.shopVo.longitude"
          :shopName="item.shopVo.shopName"
          :address="item.shopVo.address"
          :provinceCode="item.shopVo.provinceCode"
          :cityCode="item.shopVo.cityCode"
          :areaCode="item.shopVo.areaCode"
          :distance="item.shopVo.distance"
          :openTimeStr="item.shopVo.openTimeStr"
          :closeTimeStr="item.shopVo.closeTimeStr"
          :tags="item.tags"
        />
        <!--        储值-->
        <view class="flex-align-center item-store-value">
          <view
            class="money flex-align-center"
            @click="
              $Router.push({
                name: 'memberBalanceRecord',
                params: {
                  pubDomainBusinessId: item.shopVo.pubDomainBusinessId,
                },
              })
            "
            >可用余额:<text class="price" style="margin-left: 10rpx"
              >￥{{ item.balance | formatCurrency }}</text
            ></view
          >
          <view class="btns flex-align-center">
            <view>
              <u-button
                size="small"
                type="primary"
                :color="themeColor"
                shape="circle"
                @click="
                  $Router.push({
                    name: 'shopIndex',
                    params: {
                      shopId: item.shopVo.id,
                      tabActive: 1,
                    },
                  })
                "
                >储值</u-button
              >
            </view>
            <view>
              <u-button
                plain
                type="primary"
                size="small"
                shape="circle"
                :color="themeColor"
                @click="
                  $Router.push({
                    name: 'memberBalanceRecord',
                    params: {
                      pubDomainBusinessId: item.shopVo.pubDomainBusinessId,
                    },
                  })
                "
                >详情</u-button
              >
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
    <view v-else class="empty flex-align-center flex-justify-content-center">
      <list-empty />
    </view>
    <u-popup :show="isShowShopList" mode="bottom">
      <view class="businessShopList">
        <view class="header">
          <text>所有门店</text>
          <view class="close" @click="isShowShopList = false">
            <u-icon name="close" size="32rpx"
          /></view>
        </view>
        <scroll-view
          scroll-y
          class="member-business-list"
          @scrolltolower="handleBusinessScrollToLower"
          style="height: 50vh"
        >
          <view
            v-for="item in businessShopList"
            :key="item.id"
            class="list-item"
          >
            <!--        信息主体-->
            <member-list-item
              :latitude="item.latitude"
              :longitude="item.longitude"
              :logo="item.logo"
              :shopName="item.shopName"
              :address="item.address"
              :provinceCode="item.provinceCode"
              :cityCode="item.cityCode"
              :areaCode="item.areaCode"
              :distance="item.distance"
              :openTimeStr="item.openTimeStr"
              :closeTimeStr="item.closeTimeStr"
              :tags="item.tags"
            />
          </view>
        </scroll-view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import {
  getBusinessList,
  getBusinessShopList,
} from "@/service/api/sp-common/member";
import listEmpty from "@/components/baseComponents/list-enpty";
import {
  SERVER_CONFIG,
  SERVER_CONFIG_CONTENT,
} from "@/pages/sp-store/const/member";
import memberListItem from "./components/member-list-item";

export default {
  name: "index",
  components: { memberListItem, listEmpty },
  data() {
    return {
      searchCustomStyle: {
        backgroundColor: "#fff",
        width: "calc(702rpx - 24rpx - 24rpx)",
        borderRadius: "40rpx",
        height: "80rpx",
        margin: "0 auto",
        padding: "0 24rpx",
      },
      navBarHeight: 44,
      params: {
        businessName: "",
        longitude: 0,
        latitude: 0,
        pageNum: 1,
        pageSize: 10,
      },
      businessShopListParams: {
        pubDomainBusinessId: "",
        longitude: 0,
        latitude: 0,
        pageNum: 1,
        pageSize: 10,
      },
      list: [],
      businessShopList: [],
      hasNextPage: false,
      isShowShopList: false,
      isBusinessHasNextPage: false,
      tempBusinessShopInfo: null,
    };
  },
  computed: {
    themeColor({ $theme }) {
      return $theme.themeColor.primary;
    },
    imgBaseUrl() {
      return process.env.VUE_APP_BASE_FileUrl;
    },
  },
  created() {
    this.innit();
  },
  mounted() {
    this.$nextTick(() => {
      const navBarHeight = this.$refs.navBarRef.navbarHeight;
      this.uGetRect(".search-bar").then((res) => {
        this.navBarHeight = navBarHeight + res?.height || 0;
      });
    });
  },
  methods: {
    uGetRect(selector, all) {
      return new Promise((resolve) => {
        uni
          .createSelectorQuery()
          .in(this)
          [all ? "selectAll" : "select"](selector)
          .boundingClientRect((rect) => {
            if (all && Array.isArray(rect) && rect.length) {
              resolve(rect);
            }
            if (!all && rect) {
              resolve(rect);
            }
          })
          .exec();
      });
    },
    async innit(isClear) {
      const getUserLocation = await this.$getUserLocation();
      this.params.latitude = getUserLocation?.location?.latitude || "";
      this.params.longitude = getUserLocation?.location?.longitude || "";
      const {
        code,
        data: { list, hasNextPage },
      } = await getBusinessList({
        ...this.params,
      });
      if (code === 0) {
        console.log("获取数据", list);
        list.map((l) => {
          l.logoUrl = this.imgBaseUrl + l?.logoUrl;
          l.logo = this.imgBaseUrl + l?.shopVo?.logo;
          l.shopVo.distance = this.handleGetDistance(l.shopVo.distance);
          l.tags = this.handleGetServerConfig(
            l.industry,
            l.shopVo.diningConfig,
            l.shopVo.deliveryServiceConfig
          );
        });
        this.list = isClear ? list || [] : [...this.list, ...list];
        this.hasNextPage = hasNextPage;
      }
    },
    handleSearch() {
      this.$nextTick(() => {
        this.innit(true);
      });
    },
    handleScrollToLower() {
      if (!this.hasNextPage) return;
      this.params.pageNum = this.params.pageNum + 1;
      this.$nextTick(() => {
        this.innit(false);
      });
    },
    handleGetServerConfig(industry, diningConfig, deliveryServiceConfig) {
      const tags = [];
      //industry 为1解析此 diningConfig
      //industry 不为 1解析此 deliveryServiceConfig
      const config =
        Number(industry) === 1
          ? JSON.parse(diningConfig)
          : JSON.parse(deliveryServiceConfig);
      for (const key in SERVER_CONFIG) {
        if (config[key] === "true" || config[key] === true) {
          tags.push(SERVER_CONFIG_CONTENT[key]);
        }
      }
      return tags;
    },
    handleGetDistance(distance) {
      return distance
        ? distance > 1000
          ? (distance / 1000).toFixed(2) + "km"
          : distance.toFixed(2) + "m"
        : "";
    },
    async handleInnitShopList(item, isClear = false) {
      const getUserLocation = await this.$getUserLocation();
      this.tempBusinessShopInfo = isClear ? null : this.tempBusinessShopInfo;
      this.businessShopListParams.latitude =
        getUserLocation?.location?.latitude || "";
      this.businessShopListParams.longitude =
        getUserLocation.location.longitude || "";
      this.businessShopListParams.pubDomainBusinessId = item.id;
      if (isClear) {
        this.businessShopListParams.pageNum = 1;
        this.businessShopListParams.pageSize = 10;
      }
      const {
        code,
        data: { list, hasNextPage },
      } = await getBusinessShopList({
        ...this.businessShopListParams,
      });
      if (code === 0) {
        this.isBusinessHasNextPage = hasNextPage;
        this.tempBusinessShopInfo = item;
        list.map((l) => {
          l.logo = this.imgBaseUrl + l.logo;
          if (l?.distance) {
            l.distance = this.handleGetDistance(l.distance);
          }
          if (item?.industry) {
            l.tags = this.handleGetServerConfig(
              item.industry,
              l.diningConfig,
              l.deliveryServiceConfig
            );
          }
        });
        this.businessShopList = isClear
          ? list || []
          : [...this.businessShopList, ...list];
        this.$nextTick(() => {
          this.isShowShopList = true;
        });
      }
    },
    handleBusinessScrollToLower() {
      if (!this.isBusinessHasNextPage) return;
      this.businessShopListParams.pageNum += 1;
      this.$nextTick(() => {
        this.handleInnitShopList(this.tempBusinessShopInfo, false);
      });
    },
  },
};
</script>

<style scoped lang="scss">
.empty {
  height: 55vh;
}
.member-list-page {
  height: 100vh;
  overflow: hidden;
  font-family: PingFang SC;
}
.member-list-page {
  background-color: #f7f7f7;
}
.search-bar {
  width: 100vw;
  padding: 24rpx 0;
  background-color: white;
  .search-text {
    padding-right: 10rpx;
    padding-left: 24rpx;
    border-left: 1rpx solid #dddddd;
    font-size: 26rpx;
  }
}
.member-list {
  overflow: hidden;
  overflow-y: scroll;
}
.list-item {
  width: calc(710rpx - 23rpx - 26rpx);
  background: #ffffff;
  border-radius: 10rpx;
  margin: 20rpx auto;
  padding: 27rpx 23rpx 31rpx 26rpx;
}
.item-header {
  border-bottom: 1rpx solid #f7f7f7;
  padding-bottom: 47rpx;
  &-left {
    flex: 1;
    .businessName {
      font-weight: bold;
      font-size: 32rpx;
      margin-left: 17rpx;
    }
  }
  &-right {
  }
}
.item-store-value {
  padding: 16rpx 0;
  .price {
    color: #f05357;
  }
  .money,
  .btns {
    flex: 1;
  }
  .btns {
    justify-content: flex-end;
    view:first-child {
      margin-right: 15rpx;
    }
  }
}
.businessShopList {
  .header {
    position: relative;
    padding: 35rpx 0;
    text-align: center;
    border-bottom: 1rpx solid #f7f7f7;
    text {
      font-weight: bold;
      font-size: 32rpx;
    }
    .close {
      position: absolute;
      right: 39rpx;
      top: 50%;
      transform: translateY(-50%);
    }
  }
}
</style>
